package com.jz.community.basecomm.net.retrofit;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jz.community.basecomm.constant.Constant;
import com.jz.community.basecomm.net.OkHttpUtil;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Tony on 1/18/2016 16:16.
 */

public class RequestService<T> {

    private static final String DEFAULT_URL = Constant.HTTP_URL_BASE_HEAD;

    private Context mContext;
    private String current_url = DEFAULT_URL;
    private boolean isNeedHandleError = true;  //是否需要自己处理数据  默认不需要

    // @formatter:off
    final static Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
            .serializeNulls()
            .enableComplexMapKeySerialization()
            .generateNonExecutableJson()
            .enableComplexMapKeySerialization()
            .create();
    // @formatter:on

    RequestService(RequestBuilder builder) {
        handleParams(builder);
    }

    private void handleParams(RequestBuilder builder) {
        mContext = builder.getContext();
        if (null != builder.getRequestUrl()) {
            current_url = builder.getRequestUrl();
        }

        if (builder.getIsNeedHandleErrorBySelf()) {
            isNeedHandleError = builder.getIsNeedHandleErrorBySelf();
        }
    }

    /**
     * 通过此方法来与request的请求接口进行绑定
     *
     * @return 返回值如果Url地址解析出错返回NULL
     */
    public T createRequest(final Class<T> service) {
        try {
            Retrofit.Builder retrofit = null;
            if (retrofit == null) {
                retrofit = new Retrofit.Builder().addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .baseUrl(current_url);
            }
            OkHttpClient client = OkHttpUtil.getOKHttpClientInterceptor(mContext, !isNeedHandleError);
            retrofit.client(client);
            return retrofit.build().create(service);
        } catch (Exception e) {

        }
        //执行抛异常之后则进行返回null
        return null;
    }

    public <T> T createRequest(String baseUrl, final Class<T> service) {
        try {
            Retrofit.Builder retrofit = new Retrofit.Builder().addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .baseUrl(baseUrl);
            if (retrofit == null) {
                return null;
            }
            OkHttpClient client = OkHttpUtil.getOKHttpClientInterceptor(mContext, !isNeedHandleError);
            retrofit.client(client);
            return retrofit.build().create(service);
        } catch (Exception e) {

        }
        //执行抛异常之后则进行返回null
        return null;
    }
}
